var eventObj;
$(function() {
	eventObj = (function() {//include util.js menu.js json:site
		var url		= null, 
		debug 		= false,
		eid 		= null,
		keyName 	= {eid:"eid",edit:"edit",save:"save",queding:"确定",bianji:"编辑"},
		contactid 	= 0,
		contact     = {},
		action 		= "create",
		eventJSON  	= {guest:[],gids:[],ecid:0},
		init			= function() {
			_initsubButton();		//设置右侧确定/编辑按钮,左侧状态按钮
			_initDatetimepicker();	//设置日期选择器
			_initDialog();			//设置嘉宾对话框
			getstatus();//获取页面状态
		},
		
		_initsubButton = function(){
			$(".right_fnbtn").on("click",function(){
				var btnkey = {fn:$(this).attr("mm-fn"),view:$(this).attr("mm-view"),name:$(this).attr("mm-name"),call:$(this).attr("mm-call")};
				if(btnkey.fn =="save"){
					$(this).text(keyName.bianji);
					_remark(btnkey.view,btnkey.call);
					$(this).attr("mm-fn",keyName.edit);
				}else{
					$(this).text(keyName.queding);
					$(this).attr("mm-fn",keyName.save);
				}
				$(btnkey.view+"_form").toggle();
				$(btnkey.view+"_view").toggle();
			});
			$(".eflag").click(function(){
				var status = {key:$(this).attr("key"),text:$(this).text(),next:true};
				if(status.key=="2"){
					status.next = confirm("活动处于停止状态时,用户将无法查看活动的更新信息,关注该活动的用户也无法参加改活动了!");
				}
				if(status.next){
					$("#status").val(status.key);
					$(".event_status_label").text(status.text);
				}
			});
		},	
		
		_remark = function(view,fn){
			$(view+"_view .ulist").empty();
			switch(fn){
				case "eventinfo":
					var vv = [$("#name").val(),$("#title").val(),$("#subtitle").val(),$("#desc").val(),$("#weibo").val()];
					var name = ["名称","标题","副标题","描述","微博"];
					$.each(vv ,function(index,value){
						$(view+"_view .ulist").append("<li><div><span class='label label-info margin10r'>"+name[index]+"</span>"+value+"</div></li>");
					});
					break;
				case "eventlocal":
					var value = [$("#city").val(),$("#address").val()];
					var name = ["省区","详细地址"];
					$.each(value ,function(index,value){
						$(view+"_view .ulist").append("<li><div><span class='label label-info margin10r'>"+name[index]+"</span>"+value+"</div></li>");
					});
					break;
				case "eventcontact":
					if(contactid!=0){
						$(".contactpersons li").each(function(){
							var keys = [$(this).attr("data-name"),$(this).attr("data-tel1"),$(this).attr("data-tel2")];
							var value = "<p><span class='label label-info margin10r'>联系人</span>"+keys[0]+"</p><span class='label label-info margin10r'>联系电话</span>"+keys[1]+","+keys[2];
							$(view+"_view .ulist").append("<li><div>"+value+"</div></li>");
						});
					}else{
						$(view+"_view .ulist").append("<li><div>没有联系人数据</div></li>");
					}
					break;	
			}
		},
		
		_initDatetimepicker = function(){
			$(".form_date").datetimepicker({format: 'yyyy/mm/dd hh:ii',todayBtn: true,autoclose: true});
			
			$(".handmake").click(function(){
			});
		},
		
		_initDialog = function(){
			$(".canceldialog").click(function(){
				$('#myModal').modal('hide');
			});
			$(".canceldialog2").click(function(){
				$('#myModal2').modal('hide');
			});
			$("#guest_dialog_save").click(function(){
				//TODO:VINCENT
				//调用新增方法
				_showglist();
				$(".canceldialog2").click();
			});
			
			$("#clean_glist").click(function(){
				//TODO:VINCENT
				//调用清空方法
				_resetbox();
			});
			
			$(".guestitem").live("click", function(){//select guest
				  var itemstatus = $(this).attr("select"),
				  	  gid = $(this).attr("gid"),
				  	  gname = $(this).text(),
				      cancel = "0",
				      select = "1",
				  	  key = itemstatus == cancel ? select  : cancel;
				  $(this).attr("select",key);
				  switch(key){
					  case select: 
						  eventJSON.gids.push(gid);
						  eventJSON.guest.push(gname);
						  break;
					  case cancel: 
						  eventJSON.gids.pop(gid);
						  eventJSON.guest.pop(gname);
						  break;
				  }
				 var msg = "已选择"+eventJSON.gids.length+"位嘉宾";
				 if(eventJSON.gids.length==0)msg = "没有选择嘉宾"; 
				 $(".guestdialogmsg").html(msg);
			});
		},
		
		_resetbox =function(){
			eventJSON.gids = [];
			eventJSON.guest = [];
			$(".glist").empty();
			$(".guestdialogmsg").html("没有选择嘉宾");
		},
		
		_showglist = function(){			
			$(".glist").empty();
			var li_item = "";
			view = function(arg,item){
				return "<"+item+">"+arg+"</"+item+">";
			}
			$.each(eventJSON.guest,function(index,value){
				li_item += value;
				if(index< (eventJSON.guest.length-1))
					li_item += ",";
			});
			var li = view(li_item,"label");
			$(".glist").append("<div>"+li+"</div>");
		},
				
		getstatus = function(){//获取event编辑状态信息
			var key = getUrlParam(keyName.eid);
			if(key){
				var json = {url:site.web + site.getevent,eid:key};
				cb = function(data){
					if(data.code==1){
						action = "update";
						eid = key;
						//basic event info
						$.each(data.data['event'], function(index, value) {//set key/value
							if(index=="startdate"||index=="enddate"){
								$("#"+index).val(timeformat(value,8));
							}else{
								$("#"+index).val(value);
							}
						});
						//other configure
						$("#city").val(data.data['event_address']['city']);
						$("#address").val(data.data['event_address']['address']);
						var flag = data.data['event']['status'];
						$(".eflag:eq("+flag+")").click();
						var editText = $(".eflag:eq("+flag+")").text();
						$(".event_status_label").text(editText);
						
						//contact configure ,show contact div
						$(".contactperson").show();
						fill_contact("more",data.data['contact']);
						
						//show and set aboutus div value
						$(".aboutus").show();
						var aboutus = data.data['aboutus'];
						if(aboutus.ecid){
							eventJSON.ecid = aboutus.ecid;
							$("#about_title").val(aboutus.title);
							$("#about_content").text(aboutus.content);
							$("#about_url").val(aboutus.url);
						}
						//show qrcode
						$(".qrcodediv").show();
						$(".qrcodeimg").empty();
						setqrcode = function(arg){//set from google 20130805 vincent
							var link = "http://www.mediad.cn/download/mm/";
				           	var value = '<img src="http://chart.apis.google.com/chart?chs=150x150&amp;cht=qr&amp;chld=L|0&amp;chl='+link+arg+'.apk'+'" alt="'+arg+'" title="'+arg+'" width="150" height="150">';
				           	return value;
				        }
						$(".qrcodeimg").append(setqrcode(data.data['event']['qrcode']));						
					}
				};
				G(json,cb);
			}else{
				action = "create";
				$(".eflag:eq(0)").click();//默认为草稿
			}
		},
		
		add_contact = function(){//增加联系人	
			var contact = {name:$("#contact_name").val(),tel1:$("#contact_t1").val(),tel2:$("#contact_t1").val()};

			//insert
			cb = function (data){
				if(data.code==1){					
					contact.ectid = data.data;
					fill_contact("one",contact);
				}else{
					alert("添加联系人失败");
				}
			}			
			var url = site.web+"my/event/addcontact";
			contact.url = url;
			contact.uid = site.uid;
			contact.eid = eid;
			G(contact,cb);
		},
		
		del_contact = function(person){//删除联系人				
			var id = $(person).attr("data-id");
			var ectid = $(person).attr("ectid");
			//del
			cb = function (data){
				if(data.code==1){					
					$(".contactpersons>li").each(function(){
						if(id==$(this).attr("data-id")){
							$(this).remove();
						}
					});					
				}else{
					alert("删除联系人失败");
				}
			}			
			var url = site.web+"my/event/delcontact";
			var json = {url:url,ectid:ectid,eid:eid};
			G(json,cb);			
		},
		
		fill_contact = function(flag,data){//根据数据回填联系人
			
			setPerson = function(id,name,p1,p2,subid){
				if(!p1)p1="";
				if(!p2)p2="";
				var span = "<span class='label bigtextspan'>"+substring(name,8)+"<i class='icon-trash icon-white right margin5tb' data-id='"+subid+"' ectid='"+id+"' onclick='eventObj.del_contact(this)'></i></span>",
					item = "<li data-id='"+subid+"' data-name='"+name+"' data-tel1='"+p1+"' data-tel2='"+p2+"' title='电话:"+p1+","+p2+"'>"+span+"</li>";
				$(".contactpersons").prepend(item);	
			};
			
			switch(flag){
				case "one":
					//[1]增加ID
					contactid = contactid+1;
					//[2]增加节点
					setPerson(data.ectid,data.name,data.tel1,data.tel2,contactid);
					/*var span = "<span class='label bigtextspan'>"+substring(data.name,8)+"<i class='icon-trash icon-white right margin5tb' data-id='"+contactid+"' ectid='"+data.ectid+"' onclick='eventObj.del_contact(this)'></i></span>";
					var item = "<li data-id='"+contactid+"' data-name='"+data.name+"' data-tel1='"+data.tel1+"' data-tel2='"+data.tel2+"' title='电话:"+data.tel1+","+data.tel2+"'>"+span+"</li>";
					$(".contactpersons").prepend(item);	*/
					break;
				case "more":
					if(data){
						$.each(data, function(index, value) {//set key/value
							var name = data[index]['name'],
								tel1 = data[index]['phone'],
								tel2 = data[index]['extphone'],
								ectid  = data[index]['ectid'];								
							//[1]增加ID
							contactid = contactid+1;
							//[2]增加节点
							setPerson(ectid,name,tel1,tel2,contactid);
						});
					}
					break;
			}
		},
		
		seteventype = function(type){//设置活动形式
			$("#ectype").val(type);
		}, 
		
		open_dialog = function(){//模拟对话框
			$('#myModal').modal('show');
		},
		
		open_guest_dialog = function(arg){//选择嘉宾对话框
			$(arg).text("重新选择嘉宾");
			_resetbox();
			$(".guestselectlist").empty();
			cb = function (data){
				if(data.code==1){
					var list = "<ul class='guest-ul'>";
					for(var key in data.data){
						var id = data.data[key]['gid'],
							name = data.data[key]['name'];
						list += "<li class='guest-li margin5'><a class='btn guestitem' gid='"+id+"' title='"+name+"' select='0'>"+name+"</a></li>";
					}
					list+="</ul>";
					$(".guestselectlist").append(list);			
					
				}else{
					$(".guestselectlist").append("没有嘉宾信息,请录入后再进行选择");
				}
			}
			
			var url = site.web+"my/"+site.guest+"/list";
			var json = {url:url,uid:site.uid};
			G(json,cb);
			
			$('#myModal2').modal('show');
		},
		
		save_aboutus = function(){
			//about json value
			var link = site.web+"my/eventcontent/";
			var json = {requesturl:link,ecid:eventJSON.ecid,title:$("#about_title").val(),content:$("#about_content").val(),url:$("#about_url").val(),ectype:8,uid:site.uid,eid:eid};
			hidediv = function(){
				$(".about_tips").hide();
			}
			if(json.ecid==0){//create aboutus
				json.requesturl +="create";
				cb = function(data){
					eventJSON.ecid = data.data;
					$(".about_tips").show();
					setTimeout("hidediv()",1000);
				}
				GG(json,cb);
			}else{//update aboutus
				json.requesturl +="update";				
				cb = function(data){
					$(".about_tips").show();
					setTimeout("hidediv()",1000);
				}
				GG(json,cb);
			}
		},
		
		save_event = function(){//保存活动
			var web = site.web + site.module ;
			switch(action){
				case "create":
					web = web+site.creevent
					break;
				case "update":
					web = web+site.updevent
					break;
			}
			var json ={url:web,uid:site.uid,eid:eid,status:"",name:"",title:"",subtitle:"",startdate:"",enddate:"",desc:"",ectype:"",city:"",address:"",weibo:""};
			var key = null;
			var validate = {flag:false,key:""};
			$.each(json, function(index, value) {//get key/value
					if(index != "url" && index != "uid"	&& index != "eid"){//validate key by json
						key = $("#"+index).val();
						if(key==""){
							validate.flag = true;
							validate.key = index;
							return;
						}
						if(index=="startdate"||index=="enddate"){
							var dat = new Date(key);
							json[index] = dat.getTime()/1000;
						}else{
							json[index] = key;
							if(index=="weibo")//weibo no need to fill
								validate.flag = false;
						}
					}
				});
			//alertjson(json);//////////////////////////test
			if(validate.flag){
				alert("请录入"+$("#"+validate.key).attr("placeholder")+"信息.");
				return;
			}

			if(debug){
				$.each(json, function(index, value) {
					  alert(index+":"+value);
					});
				}
			complete = function(data){
				open_dialog();
		  	  //alert(data.code+","+data.message);////////////////////////////test
		    };
			G(json,complete);
		},
		callback = function(func){//回调函数
			func();
		};
		
		return { 
			init :init,
			save_event 	: save_event,
			save_aboutus: save_aboutus,
			add_contact : add_contact,
			del_contact : del_contact,
			open_dialog : open_dialog,
			open_guest_dialog : open_guest_dialog,
			seteventype : seteventype,
			callback 	: callback
		};
	})();
	eventObj.init();
}); 
